import type {ResponsePaginationData} from '@/utils/request';
import type {RequestData} from '@ant-design/pro-table';
import type {QueryListParams, TableListItem} from './data';
import moment from 'moment';
import {xstatus} from '../utils/utils';
import {request} from 'umi';

/**
 * 获取设备上报历史记录
 * @param deviceNo
 * @param params
 */
export async function getDeviceMoteData(params: QueryListParams): Promise<RequestData<TableListItem>> {
  const {page = 1, pageSize = 20, deviceNo, type = 'status', recordTime} = params;

  if (!deviceNo) {
    return {
      success: false,
      total: 0,
      data: [],
    };
  }

  const [startTime, endTime] = recordTime || [];

  const url = type === 'status' ? `/get_device_mote_status_list` : `/get_device_mote_info_list`;

  const res: ResponsePaginationData<{
    id: any;
    createAt: number;
    stateUpdateAt: number;
    [key: string]: any;
  }> = await request(url, {
    params: {
      page,
      pageSize,
      startTime: startTime ? startTime.format('YYYY-MM-DD HH:mm:00') : undefined,
      endTime: endTime ? endTime.format('YYYY-MM-DD HH:mm:00') : undefined,
    },
  });

  return {
    success: true,
    total: res.data.total,
    data: res.data.list.map(item => {
      const {id, createAt, stateUpdateAt, ...others} = item;

      let str = '0000-00-00 00:00:00';
      if (stateUpdateAt) {
        const date = new Date(stateUpdateAt);
        str = moment(date).format('YYYY-MM-DD HH:mm:ss');
      }

      return {
        id: String(id),
        recordTime: createAt ? new Date(createAt) : new Date(),
        stateUpdateAt: str || '',
        deviceNo: item.deviceNo,
        type: item.type,
        status: item.state ? item.state : '',
        statusList: xstatus.parses(item.statusBox),
        statusBox: item.statusBox,
        count: item.count ? item.count : '',
        rtRssi: item.rtRssi ? item.rtRssi : '',
        rtSnr: item.rtSnr ? item.rtSnr : '',
        batt: item.batt ? item.batt : '',
        temp: item.temp ? item.temp : '',
        imei: item.imei ? item.imei : '',
        sim: item.sim ? item.sim : '',
        ...others,
      };
    }),
  };
}
